package com.example.demo.outlook;


import com.azure.core.credential.TokenRequestContext;
import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.microsoft.graph.authentication.IAuthenticationProvider;
import com.microsoft.graph.models.Attachment;
import com.microsoft.graph.requests.GraphServiceClient;
import com.microsoft.graph.requests.MessageCollectionPage;
import com.microsoft.graph.requests.AttachmentCollectionPage;
import com.microsoft.graph.models.Message;
import com.microsoft.graph.models.FileAttachment;
import okhttp3.Request;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.jetbrains.annotations.NotNull;

import java.net.URL;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author linls
 */
public class OutLookAttachment {

    public static void main(String[] args) {
        // 从 Azure 应用注册获取的信息
        final String tenantId = "aaf1697c-4473-4326-bd03-7d25effca28b";
        final String clientId = "6169a47e-3a2e-4c47-87ac-d91acc524a20";
        final String clientSecret = "WOP8Q~noPAxMZBAek.nI4_kuLVWUA_h93Eh0nbNw";

        // 1. 构建认证凭证
        ClientSecretCredential credential = new ClientSecretCredentialBuilder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .tenantId(tenantId)
                .build();

        IAuthenticationProvider authenticationProvider = new IAuthenticationProvider() {
            @NotNull
            @Override
            public CompletableFuture<String> getAuthorizationTokenAsync(@NotNull URL url) {
                CompletableFuture<String> future = new CompletableFuture<>();
                String accessToken = credential.getTokenSync(
                        new TokenRequestContext()
                                .addScopes("https://graph.microsoft.com/.default") // 请求应用程序权限范围
                ).getToken();
                future.complete(accessToken);

                return future;

             }
        };

        // 2. 创建经过身份验证的 Graph 客户端
        GraphServiceClient graphClient=   GraphServiceClient.builder().authenticationProvider(authenticationProvider).buildClient();
        // 3. 使用 Graph 客户端 API 获取邮件和附件
        try {
            // 获取用户邮箱（例如 user@domain.com）中的邮件
            // 注意：使用 Client Credentials Flow 时，你需要指定具体的用户邮箱
            String userPrincipalName = "yangmk@chint.com";

            MessageCollectionPage messages = graphClient.users(userPrincipalName)
                    .messages()
                    .buildRequest()
                    .select("subject,hasAttachments")
                    .top(20) // 获取前10封邮件
                    .get();

            if (messages != null) {
                for (Message message : messages.getCurrentPage()) {
                    System.out.println("Subject: " + message.subject);
                    System.out.println("Has Attachments: " + message.hasAttachments);

                    // 如果邮件有附件，则获取附件列表
                    if (Boolean.TRUE.equals(message.hasAttachments)) {
                        AttachmentCollectionPage attachments = graphClient.users(userPrincipalName)
                                .messages(message.id)
                                .attachments()
                                .buildRequest()
                                .get();

                        if (attachments != null) {
                            List<Attachment> fileAttachments = attachments.getCurrentPage();
                            for (Attachment attachment : fileAttachments) {
                                System.out.println("  -> Attachment Name: " + attachment.name);
                                System.out.println("  -> Content Type: " + attachment.contentType);
                                System.out.println("  -> Size: " + attachment.size + " bytes");

                                // 如果你想下载附件内容
                                // byte[] fileBytes = attachment.contentBytes;
                                // 然后可以使用 FileOutputStream 等将 fileBytes 写入文件
                                // String filePath = "/path/to/save/" + attachment.name;
                                // try (FileOutputStream stream = new FileOutputStream(filePath)) {
                                //     stream.write(fileBytes);
                                // }
                                // System.out.println("Attachment saved to: " + filePath);
                            }
                        }
                    }
                    System.out.println("-----");
                }
            }
        } catch (Exception e) {
            System.err.println("Error retrieving messages or attachments: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

